<template>
  <div class="app">
    <div v-if="debug" class="debug">
      <a-button type="danger" class="debug-button" @click="showConfirm">
        退出本地调试
      </a-button>
    </div>
    <ui-layout>
      <ui-sub-layout
        :header="headerVisible"
        @sidebar-selected="onSidebarSelected"
      >
        <template slot="logo_small">
          <img :src="logo" />
        </template>
        <template slot="logo">
          <img :src="logo" style="width:160px;margin-left: 60px;" />
        </template>
        <!-- <template slot="header-user-prefix">
          <user-prefix></user-prefix>
        </template> -->
        <template slot="sidebar-prefix">
          <div v-if="title" class="sidebar-title">{{ title }}</div>
        </template>
        <template>
          <div v-show="isQiankun" id="app-container"></div>
          <div v-show="!isQiankun" id="router-container">
            <router-view :key="$route.path"></router-view>
          </div>
        </template>
      </ui-sub-layout>
    </ui-layout>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import logo from '@/assets/images/logo-citycode.svg'
import logoSmall from '@/assets/images/logo-small.svg'
// import { request } from '@/core/sdk/request'
import UserPrefix from '@/pages/index/views/center/user-prefix'
import * as UTILS from '@/util/index'
import { initGlobalState } from 'qiankun'
import menuConfig from '../../../config/menu.config'
import headerConfig from '../../../config/header.config'
import { setHeaderVisible } from './frame/methods'

const routeModuleReg = [/\/operation-analysis/,/\/payment/] // [/\/developing$/, /\/operation-analysis/]
const isRouteModulePath = function() {
  const path = window.location.pathname
  const res =  !routeModuleReg.some(item => {
    const isRouteModule = path.match(item)
    return isRouteModule && isRouteModule.length > 0
  })
  console.log('是否采用内部路由', !res)
  return res
}


export default {
  components: { UserPrefix },
  computed: {
    ...mapState('frame', {
      headerVisible: 'headerVisible'
    })
  },
  data() {
    return {
      title: null,
      logo,
      logoSmall,
      publicPath: process.env.VUE_APP_ROUTER_BASE,
      debug: localStorage.getItem('moduleEntry'),
      // 当为/developing路径时，则采用前端路由
      // isQiankun: !window.location.pathname.match(/\/developing$/) && !window.location.pathname.match(/\/operation-analysis/),
      isQiankun: isRouteModulePath(),
      menuTreeList: null, // 从权限中心获取的用户菜单列表，已处理成树形结构
      menuConfig: null, // 经处理后的菜单配置
      headerConfig: null // 经处理后的header配置
    }
  },
  watch: {
    $route(to, from) {
      this.setSidebarConfig(to.path)
      this.setMenuMode(to.path)
      this.setHeaderVisibleState(to.path)
      this.isQiankun = isRouteModulePath()
      console.log('______isQiankun_____', this.isQiankun)
    }
  },
  mounted() {
    this.mainVuexMutation()
    this.mainVuexAction()
    this.actionFromSub()
    this.setSideBarVisibleState()
  },
  methods: {
    setSideBarVisibleState() {
      const params = window.location.search
      if (!params) {
        return
      }
      const paths = params.split('?')
      const needHide =
        paths &&
        paths[1].split('&').some(item => {
          const key = item.split('=')
          if (key[0] === 'hideSideBar') {
            return key[1] === '1'
          }
        })
      this.$store.commit(
        `global/${this.$storeGlobalTypes.SET_SIDEBAR_STATUS}`,
        !needHide
      )
    },
    actionFromSub() {
      const that = this
      const qiankunState = { menu_name: '' }
      this.action = initGlobalState(qiankunState)
      this.action.onGlobalStateChange((state, pre) => {
        // 复制行为
        if (state.qiankun_action === 'HIGHLIGHT_MENU') {
          that.$store.commit(
            `global/${that.$storeGlobalTypes.SET_CURRENT_ENTRY}`,
            state.menu_name
          )
        }
      })
    },
    showConfirm() {
      this.$confirm({
        title: '是否退出本地调试模式',
        onOk() {
          return new Promise((resolve, reject) => {
            localStorage.removeItem('moduleEntry')
            localStorage.removeItem('moduleName')
            window.location.reload()
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {}
      })
    },
    /**
     * 调用全局Action例子
     */
    mainVuexAction() {
      this.fetchUserMenuList(list => {
        this.menuConfig = UTILS.generateMenuConfig(list)
        this.headerConfig = UTILS.generateHeaderConfig(list)
        console.log('this.menuConfig.', this.menuConfig, list)
        console.log('this.headerConfig', this.headerConfig)
        this.setMenuMode()
        this.setSidebarConfig()
        this.setHeaderConfig()
      })
    },
    /**
     * 调用全局Mutation例子
     */
    mainVuexMutation() {
      // this.setHeaderVisibleState(window.location.pathname)
      this.registerEvent()
    },
    /**
     * 点击侧栏子元素事件
     * @param e
     * @param next 完成自己的逻辑后必须执行，不然不会执行默认的router.push操作
     */
    onSidebarSelected(e, next) {
      next()
    },
    fetchUserMenuList(cb) {
      if (!this.menuTreeList) {
        UTILS.fetchMenuList()
          .then(res => {
            if (res && res.length) {
              this.menuTreeList = UTILS.listToTree(res)
              cb && cb(this.menuTreeList)
            }
          })
          .catch(err => {
            this.$message.error('获取用户菜单失败')
            console.log(err)
            this.menuConfig = menuConfig
            this.headerConfig = headerConfig
          })
      } else {
        cb && cb(this.menuTreeList)
      }
    },
    setSidebarConfig(path) {
      path = path || window.location.pathname
      const target = Object.keys(this.menuConfig).find(
        key => path.indexOf(`${process.env.VUE_APP_ROUTER_BASE}${key}`) > -1
      )
      if (target) {
        this.$store.dispatch(
          this.$storeGlobalTypes.SET_SIDEBAR_CONFIG,
          this.menuConfig[target].menuData
        )
      }
      this.setHeaderHighLight()
    },
    setHeaderConfig() {
      // 点击当前页不跳转
      this.headerConfig.entryList.map(item => {
        if (typeof item === 'object' && item[0] === 'admin') {
          for (let i = 1; i < item.length; i++) {
            if (
              item[i].url &&
              window.location.pathname.indexOf(item[i].url) > -1
            ) {
              item[i].url = '#'
            }
          }
        } else {
          return item
        }
      })

      Object.keys(this.headerConfig.entry).map(key => {
        const url = this.headerConfig.entry[key].url || ''
        if (window.location.pathname.indexOf(url) > -1) {
          this.headerConfig.entry[key].url = '#'
        }
      })
      // 注意： 头部的跳转要调整
      this.$store.dispatch(
        this.$storeGlobalTypes.SET_HEADER_MENU,
        this.headerConfig
      )

      this.setHeaderHighLight()
    },
    // 设置顶部高亮
    setHeaderHighLight() {
      setTimeout(() => {
        Object.keys(this.headerConfig.entry).map(entry => {
          if (
            window.location.pathname.indexOf(
              `${process.env.VUE_APP_ROUTER_BASE}/${entry}`
            ) === 0
          ) {
            this.$store.commit(
              `global/${this.$storeGlobalTypes.SET_CURRENT_ENTRY}`,
              entry
            )
          }
        })
      }, 10)
    },
    // 如果path里边含有hideHeader，就隐藏头部header
    setHeaderVisibleState(path) {
      const subPathList = path.split('/')
      if (subPathList && subPathList.length) {
        if (subPathList.find(item => item === 'hideHeader')) {
          setHeaderVisible(false)
        } else {
          setHeaderVisible(true)
        }
      } else {
        setHeaderVisible(true)
      }
    },
    setMenuMode(path) {
      path = path || window.location.pathname
      const target = Object.keys(this.menuConfig).find(
        key => path.indexOf(key) > -1
      )

      const adminEnum = {
        '/admin/user': '组织用户'
      }
      const titleKey = Object.keys(adminEnum).find(
        key => path.indexOf(key) > -1
      )

      this.title = adminEnum[titleKey] || null
      if (target) {
        if (this.menuConfig[target].menuData.length > 0) {
          this.$store.commit(
            `global/${this.$storeGlobalTypes.SET_MENU_MODE}`,
            this.menuConfig[target].menuMode
          )
        } else {
          this.$store.commit(
            `global/${this.$storeGlobalTypes.SET_SIDEBAR_STATUS}`,
            false
          )
        }
      } else {
        // 没有找到的话，就隐藏左侧菜单
        this.$store.commit(
          `global/${this.$storeGlobalTypes.SET_SIDEBAR_STATUS}`,
          false
        )
      }
    },

    /**
     * store中的事件注册
     * 预留事件：
     *    handleLogin: 登录
     *    handleLogout: 登出
     */
    registerEvent() {
      const self = this
      // 注册事件
      this.$store.commit(`global/${this.$storeGlobalTypes.REGISTER_EVENT}`, {
        handleLogin: self.onHandleLogin,
        handleLogout: self.onHandleLogout
      })
    },
    /**
     * 用户登录示例
     */
    onHandleLogin() {
      // 用户登录示例
      return new Promise(resolve => {
        this.$showLoading('登录中，请稍后')
        setTimeout(() => {
          // 需要return对应的用户信息及menu
          const obj = {
            info: {
              name: '管理员'
            } /*,
            menu: [
              {
                name: '跳转到某个地址',
                url: 'https://www.qq.com/'
              }
            ] */
          }
          this.$hideLoading()
          this.$message.success('登录成功')
          resolve(obj)
        }, 2000)
      })

      // 兼容之前主动调用action的模式
      // this.$store.dispatch(this.$storeGlobalTypes.SET_USER_INFO, {
      //   isLogin: true,
      //   info: {
      //     name: '我是很长的用户名'
      //   },
      //   menu: [
      //     {
      //       name: '跳转到某个地址',
      //       url: 'https://www.qq.com/'
      //     }
      //   ]
      // })
    },
    /**
     * 用户登出示例
     */
    onHandleLogout() {
      return new Promise(resolve => {
        this.$showLoading('我这里可能是一些登出前的操作')
        setTimeout(() => {
          this.$message.success('登出成功')
          this.$hideLoading()
          resolve()
        }, 2000)
      })
    }
  }
}
</script>

<style lang="scss">
body {
  // 这里$--background-color--main来自于'/src/assets/styles/common/_var.scss'
  background-color: $--background-color--main;
}
#app-container {
  width: 100%;
}
#router-container {
  width: 100%;
}
.debug {
  position: relative;
  top: 0px;
  .debug-button {
    position: absolute;
    left: 70%;
    z-index: 100;
  }
}
.nav {
  padding: 30px;

  a {
    font-weight: bold;
    color: #2c3e50;

    *.router-link-exact-active {
      color: #42b983;
    }
  }
}

.app {
  .sub-sidebar__box {
    position: static !important;
  }
  color: #2c3e50;
}

.sub-content {
  padding: 0 !important;
}

.sub-header__interrelation {
  padding-left: 0 !important;
}

.sub-sidebar__interrelation {
  z-index: 0 !important;
}

.sidebar-title {
  padding-left: 24px;
  display: flex;
  align-items: center;
  height: 56px;
  font-size: 18px;
  font-weight: 600;
  text-align: left;
  border-top: 1px solid #e8e8e8;
  border-bottom: 1px solid #e8e8e8;
}

.sub-header__horizontal {
  padding-left: 0 !important;
}

.sub-content__main {
  padding-top: 0 !important;
  max-width: 100% !important;
  width: 100% !important;
  margin: 0 !important;
}

.sub-content__bg {
  display: none !important;
}

.sub-header__secondary.ant-menu-horizontal {
  &:before {
    content: '设置';
    position: absolute;
    font-size: 20px;
    color: #1d1f25;
    line-height: 56px;
    left: 24px;
  }
}

.sub-header__logo {
  vertical-align: top;
  img {
    max-height: none !important;
  }
}

.sub-header__mid {
  vertical-align: top;
  width: calc(100% - 450px);
}

.header-popup-entry {
  padding-left: 40px !important;
  overflow: hidden;
}
</style>
